<template>
  <div class="app-container">
    
    <!-- 按钮区域 -->
    <div class="mb20">
      <el-button type="primary" icon="el-icon-plus" @click="handleAddParent" v-hasPermi="['sb:equipment-types:add']">新增顶级分类</el-button>
      <el-button type="info" plain icon="el-icon-sort" @click="toggleExpandAll">{{ isExpandAll ? '折叠所有' : '展开所有' }}</el-button>
      <el-button type="success" plain icon="el-icon-refresh" @click="refreshTreeData">刷新数据</el-button>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
        <el-input
            placeholder="请输入设备类型名称"
          v-model="queryParams.typeName"
            prefix-icon="el-icon-search"
            style="width: 300px"
          clearable
            @keyup.enter.native="handleQuery">
          </el-input>
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </div>
    
    <!-- 表格区域 -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      row-key="typeId"
      :expand-row-keys="expandRowKeys"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      border
      style="width: 100%"
      @row-click="handleRowClick">
      <el-table-column
        prop="typeName"
        label="分类名称"
        width="300">
        <template slot-scope="scope">
          <!-- 更明显的父子节点区分 -->
          <span v-if="hasChildren(scope.row)" class="folder-icon">
            <i class="el-icon-folder-opened" style="color: #FFCA28; font-size: 18px; margin-right: 8px;"></i>
            <span style="font-weight: 600; color: #303133;">{{ scope.row.typeName || '未命名' }}</span>
          </span>
          <span v-else class="file-icon">
            <i class="el-icon-document" style="color: #78909C; font-size: 16px; margin-right: 8px;"></i>
            <span>{{ scope.row.typeName || '未命名' }}</span>
          </span>
          
          <!-- 子节点数量标签 -->
          <el-tag 
            v-if="hasChildren(scope.row)" 
            size="mini" 
            type="info" 
            style="margin-left: 5px;">
            {{ scope.row.children.length }}个子项
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="typeCode"
        label="分类编码"
        width="150">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createBy"
        label="创建人"
        width="120">
      </el-table-column>
      <el-table-column label="是否启用" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.typeStatus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注">
        <template slot-scope="scope">
          {{ scope.row.remark || '无' }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="300">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click.stop="handleAddChild(scope.row)"
            style="color: #0d84ff;"
            v-hasPermi="['sb:equipment-types:add']">
            添加子类
          </el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button
            type="text"
            size="small"
            @click.stop="handleUpdate(scope.row)"
            style="color: #0d84ff;"
            v-hasPermi="['sb:equipment-types:edit']">
            编辑
          </el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button
            type="text"
            size="small"
            @click.stop="handleDelete(scope.row)"
            style="color: #ff4d4f;"
            v-hasPermi="['sb:equipment-types:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改设备类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类型编码" prop="typeCode">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="form.typeCode" placeholder="请输入类型编码" :disabled="autoGenerateCode" />
            </el-col>
            <el-col :span="8">
              <el-checkbox v-model="autoGenerateCode" @change="handleAutoCodeChange">自动生成</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入设备类型名称" @blur="handleTypeNameBlur" />
        </el-form-item>
        <el-form-item v-if="dialogType !== 'addParent'" label="上级类型" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="typeOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择上级类型"
          />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="form.typeStatus">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipmentType, listAllEquipmentType, getEquipmentType, delEquipmentType, addEquipmentType, updateEquipmentType, checkTypeCodeUnique, generateCodeFromName, changeEquipmentTypeStatus } from "@/api/sb/equipmentTypes";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "EquipmentType",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 设备类型表格数据
      typeList: [],
      // 设备类型树选项
      typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 对话框类型
      dialogType: '',
      // 状态数据字典
      statusOptions: [],
      // 自动生成编码
      autoGenerateCode: false,
      // 已展开的行key
      expandRowKeys: [],
      // 查询参数
      queryParams: {
        typeName: undefined,
        typeCode: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级类型不能为空", trigger: "blur" }
        ],
        typeCode: [
          { 
            validator: (rule, value, callback) => {
              // 如果是自动生成模式，跳过必填验证
              if (this.autoGenerateCode) {
                callback();
                return;
              }
              // 手动模式下进行必填验证
              if (!value) {
                callback(new Error('设备类型编码不能为空'));
                return;
              }
              callback();
            }, 
            trigger: "blur" 
          },
          { 
            validator: this.validateTypeCode, 
            message: "设备类型编码已存在", 
            trigger: "blur" 
          }
        ],
        typeName: [
          { required: true, message: "设备类型名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // 时间格式化
    parseTime,

    /** 查询设备类型列表 */
    getList() {
      this.loading = true;
      // 使用listAllEquipmentType获取所有设备类型用于构建树状结构
      listAllEquipmentType(this.queryParams).then(response => {
        // 添加空值检查，确保response.data存在
        const data = response.data || [];
        console.log("原始数据:", data);
        
        // 手动构建树结构
        this.buildTreeData(data);
      }).catch(error => {
        console.error("获取设备类型列表失败:", error);
        this.loading = false;
        this.typeList = [];
      });
    },
    
    /** 手动构建树结构 */
    buildTreeData(data) {
      if (!data || data.length === 0) {
        this.typeList = [];
        this.loading = false;
        return;
      }
      
      // 创建ID到节点的映射
      const nodeMap = {};
      const result = [];
      
      // 复制数据，避免修改原始数据
      const clonedData = data.map(item => ({
        ...item,
        children: [] // 确保每个节点都有children数组
      }));
      
      // 构建节点映射
      clonedData.forEach(node => {
        nodeMap[node.typeId] = node;
      });
      
      // 构建树结构
      clonedData.forEach(node => {
        // 如果有父节点且该父节点存在
        if (node.parentTypeId !== null && 
            node.parentTypeId !== undefined && 
            node.parentTypeId !== 0 && 
            nodeMap[node.parentTypeId]) {
          // 添加到父节点的children
          if (!nodeMap[node.parentTypeId].children) {
            nodeMap[node.parentTypeId].children = [];
          }
          nodeMap[node.parentTypeId].children.push(node);
        } else {
          // 顶级节点直接添加到结果
          result.push(node);
        }
      });
      
      console.log("构建的树结构:", result);
      this.typeList = result;
      
      // 如果搜索条件存在，则自动展开所有节点
      if (this.queryParams.typeName) {
        this.isExpandAll = true;
        this.expandRowKeys = this.getAllNodeIds(this.typeList);
      }
      
      // 确保表格重新渲染
      this.refreshTable = false;
          this.$nextTick(() => {
        this.refreshTable = true;
        this.loading = false;
      });
    },

    /** 递归获取子节点 */
    getChildrenTypes(parentId, allTypes) {
      const children = allTypes.filter(item => item.parentTypeId === parentId);
      children.forEach(child => {
        const subChildren = this.getChildrenTypes(child.typeId, allTypes);
        if (subChildren.length > 0) {
          child.children = subChildren;
        }
      });
      return children;
    },
    
    /** 转换设备类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeId,
        label: node.typeName,
        children: node.children
      };
    },
    /** 验证类型编码唯一性 */
    validateTypeCode(rule, value, callback) {
      // 如果是自动生成模式，跳过验证
      if (this.autoGenerateCode) {
        callback();
        return;
      }
      
      // 手动输入模式下的验证
      if (!value) {
        callback(new Error('设备类型编码不能为空'));
        return;
      }
      
      // 验证编码唯一性
      const params = {
        typeCode: value,
        typeId: this.form.typeId
      };
      checkTypeCodeUnique(params).then(response => {
        if (!response.data) {
          callback();
        } else {
          callback(new Error('设备类型编码已存在'));
        }
      });
    },
    /** 自动生成编码选项变更 */
    handleAutoCodeChange(val) {
      if (val) {
        // 清空编码字段，让系统自动生成
        this.form.typeCode = '';
        // 如果已有类型名称，立即生成编码
        if (this.form.typeName) {
          this.generateCodeFromTypeName();
        }
      }
    },
    /** 类型名称失去焦点时自动生成编码 */
    handleTypeNameBlur() {
      if (this.autoGenerateCode && this.form.typeName) {
        this.generateCodeFromTypeName();
      }
    },
    /** 查询设备类型下拉树结构 */
    getTreeselect() {
      listEquipmentType().then(response => {
        this.typeOptions = [];
        // 添加空值检查
        const data = response.data || response.rows || [];
        const rootData = { typeId: 0, typeName: '顶级类型', children: [] };
        if(data && data.length > 0) {
          // 手动构建树结构
          const nodeMap = {};
          data.forEach(node => {
            if (!node.children) node.children = [];
            nodeMap[node.typeId] = node;
          });
          
          data.forEach(node => {
            if (node.parentTypeId !== null && 
                node.parentTypeId !== undefined && 
                node.parentTypeId !== 0 && 
                nodeMap[node.parentTypeId]) {
              if (!nodeMap[node.parentTypeId].children) {
                nodeMap[node.parentTypeId].children = [];
              }
              nodeMap[node.parentTypeId].children.push(node);
            } else {
              rootData.children.push(node);
            }
          });
        }
        this.typeOptions.push(rootData);
      }).catch(error => {
        console.error("获取类型树结构失败:", error);
        this.typeOptions = [{
          typeId: 0,
          typeName: '顶级类型',
          children: []
        }];
      });
    },
    /** 行点击事件处理 */
    handleRowClick(row) {
      // 切换展开状态
      if (this.hasChildren(row)) {
        const index = this.expandRowKeys.indexOf(row.typeId);
        if (index > -1) {
          this.expandRowKeys.splice(index, 1); // 已展开，则关闭
        } else {
          this.expandRowKeys.push(row.typeId); // 未展开，则展开
        }
      }
    },
    
    /** 判断是否有子节点 */
    hasChildren(row) {
      return row.children && row.children.length > 0;
    },
    
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      
      if (this.isExpandAll) {
        // 展开所有节点，递归获取所有节点ID
        this.expandRowKeys = this.getAllNodeIds(this.typeList);
      } else {
        // 折叠所有节点
        this.expandRowKeys = [];
      }
      
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    
    /** 递归获取所有节点ID */
    getAllNodeIds(nodes) {
      if (!nodes || !nodes.length) return [];
      
      let ids = [];
      nodes.forEach(node => {
        ids.push(node.typeId);
        if (node.children && node.children.length) {
          ids = ids.concat(this.getAllNodeIds(node.children));
        }
      });
      return ids;
    },
    /** 刷新数据 */
    refreshTreeData() {
      // 显示加载中
      this.loading = true;
      this.$message({
        message: '正在刷新数据...',
        type: 'info',
        duration: 1000
      });
      
      // 重新获取数据
      this.getList();
      
      // 重置展开状态
      this.refreshTable = false;
      this.$nextTick(() => {
        this.refreshTable = true;
        this.loading = false;
        this.$message({
          message: '数据刷新成功',
          type: 'success',
          duration: 1500
        });
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        typeName: undefined,
        typeCode: undefined,
        status: undefined
      };
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 新增顶级类型按钮操作 */
    handleAddParent() {
      this.reset();
      this.dialogType = 'addParent';
      this.autoGenerateCode = true; // 默认开启自动生成
      this.open = true;
      this.title = "添加顶级分类";
      this.form = {
        parentId: null,
        typeName: undefined,
        typeCode: undefined,
        typeStatus: "0"
      };
    },
    /** 新增子类型按钮操作 */
    handleAddChild(row) {
      this.reset();
      this.dialogType = 'addChild';
      this.autoGenerateCode = true; // 默认开启自动生成
      this.getTreeselect();
      this.open = true;
      this.title = "添加子类";
      this.form = {
        parentId: row.typeId,
        typeName: undefined,
        typeCode: undefined,
        typeStatus: "0"
      };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.dialogType = 'edit';
      this.autoGenerateCode = false; // 编辑时默认关闭自动生成
      this.getTreeselect();
      getEquipmentType(row.typeId).then(response => {
        this.form = response.data;
        this.form.parentId = this.form.parentTypeId;
        this.open = true;
        this.title = "修改设备类型";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果是自动生成编码模式，确保有编码
          if (this.autoGenerateCode) {
            if (!this.form.typeName) {
              this.$message.warning('自动生成编码需要先输入类型名称');
              return;
            }
            
            // 如果编码为空，先尝试生成，然后等待生成完成
            if (!this.form.typeCode) {
              this.generateCodeFromTypeName().then(() => {
                // 编码生成完成后，继续提交
                this.submitFormData();
              }).catch(error => {
                console.error('生成编码失败:', error);
                this.$message.error('生成编码失败，请手动输入编码');
              });
              return;
            }
          }
          
          // 直接提交
          this.submitFormData();
        }
      });
    },

    /** 实际提交数据的方法 */
    submitFormData() {
      // 准备提交数据
      const submitData = {
        ...this.form,
        parentTypeId: this.form.parentId,
        typeSuperior: this.form.parentId
      };
      
      // 如果是顶级类型，确保parentTypeId为null
      if (this.dialogType === 'addParent' || submitData.parentId === 0 || submitData.parentId === null) {
        submitData.parentTypeId = null;
        submitData.typeSuperior = null;
      } else {
        // 确保子类型有正确的父ID
        submitData.parentTypeId = this.form.parentId;
        submitData.typeSuperior = this.form.parentId;
      }
      
      // 添加调试信息
      console.log('提交的数据:', submitData);
      console.log('对话框类型:', this.dialogType);
      console.log('父ID:', this.form.parentId);
      console.log('父类型ID:', submitData.parentTypeId);
      console.log('typeSuperior:', submitData.typeSuperior);
      
      if (submitData.typeId !== undefined) {
        updateEquipmentType(submitData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          // 刷新数据，保持树状结构展示
          this.getList();
        }).catch(error => {
          console.error("修改失败:", error);
        });
      } else {
        addEquipmentType(submitData).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          // 刷新数据，保持树状结构展示
          this.getList();
        }).catch(error => {
          console.error("新增失败:", error);
        });
      }
    },

    /** 根据类型名称生成编码 */
    generateCodeFromTypeName() {
      return new Promise((resolve, reject) => {
        if (!this.form.typeName) {
          reject(new Error('请先输入类型名称'));
          return;
        }
        
        generateCodeFromName(this.form.typeName).then(response => {
          this.form.typeCode = response.data;
          // 触发表单验证更新
          this.$nextTick(() => {
            this.$refs.form.validateField('typeCode');
          });
          resolve();
        }).catch(error => {
          console.error('生成编码失败', error);
          reject(error);
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 首先检查是否有子类型
      if (row.children && row.children.length > 0) {
        this.$modal.msgError(`该类型下还有${row.children.length}个子类型，不能删除`);
            return;
          }
          
      this.$modal.confirm('是否确认删除设备类型名称为"' + row.typeName + '"的数据项？').then(function() {
        return delEquipmentType(row.typeId);
      }).then(() => {
        // 刷新数据，保持树状结构展示
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((error) => {
        if (error) {
          console.error("删除失败:", error);
        }
      }); 
    },
    /** 启用/禁用状态修改 */
    handleStatusChange(row) {
      let text = row.typeStatus === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.typeName + '"设备类型吗?').then(function() {
        return changeEquipmentTypeStatus(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function(error) {
        // 当操作失败时，将开关状态恢复到原来的状态
        if (error !== 'cancel') {
          // 接口返回的错误，将开关状态切换回去
          row.typeStatus = row.typeStatus === "0" ? "1" : "0";
          // 不显示任何错误消息，让全局错误处理器来显示服务器返回的消息
        } else {
          // 用户取消操作，同样需要将开关状态切换回去
          row.typeStatus = row.typeStatus === "0" ? "1" : "0";
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        typeId: undefined,
        parentId: undefined,
        typeName: undefined,
        typeCode: undefined,
        typeStatus: "0",
        remark: undefined
      };
      // 不重置autoGenerateCode，让各个操作自己设置
      this.resetForm("form");
    }
  }
};
</script> 

<style scoped>
.mb20 {
  margin-bottom: 20px;
}

.search-area {
  background-color: #f5f7fa;
  padding: 18px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.folder-icon i,
.file-icon i {
  font-size: 16px;
  margin-right: 5px;
}

.folder-icon i {
  color: #FFCA28;
}

.file-icon i {
  color: #78909C;
}

/* 优化树状表格缩进 */
.app-container ::v-deep .el-table__indent {
  padding-left: 20px !important;
}

/* 强化展开/折叠图标 */
.app-container ::v-deep .el-table__expand-icon {
  font-size: 14px;
  height: 24px;
  width: 24px;
  line-height: 24px;
  color: #555;
  border-radius: 2px;
}

.app-container ::v-deep .el-table__expand-icon .el-icon-arrow-right {
  transition: transform 0.2s ease-in-out;
  font-size: 14px;
}

.app-container ::v-deep .el-table__expand-icon--expanded .el-icon-arrow-right {
  transform: rotate(90deg);
}

.el-divider--vertical {
  height: 1em;
  margin: 0 8px;
}

/* 高亮鼠标悬停行 */
.app-container ::v-deep .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

/* 父节点行样式 */
.app-container ::v-deep .el-table__row.is-parent > td {
  background-color: #f5f7fa;
}
</style> 